var constraintType;
var imgDir;

function setProperties(pImgDir,_constraintType){
	imgDir=pImgDir;
	constraintType=_constraintType;
}


/*
 * Genera un objeto XMLHttpRequest dependiendo del navegador utilizado
 * Generates an XMLHttpRequest object according to the used web browser
 */
function getXmlHttpObject(){
	var httpRequest=null;
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
		httpRequest= new XMLHttpRequest();
	}else if (window.ActiveXObject){
		// code for IE6, IE5
		httpRequest= ActiveXObject("Microsoft.XMLHTTP");
	}
	return httpRequest;
}

var httpRequest;
var elementId;

function getColumnsByTable(id){	
	elementId="refColumns";	
	xmlhttp=getXmlHttpObject();
	if (xmlhttp==null){
	  alert ("Your browser does not support AJAX!");
	  return;
	}
	
	var url="fk.functions.php";
	url+="?function= getColumnsByTable";
	url+="&id="+id;
	url+="&sid="+Math.random();
	xmlhttp.onreadystatechange=stateChangedForRefColumns;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);	
}

function stateChangedForRefColumns(){
	if (xmlhttp.readyState==4){
		responseText=xmlhttp.responseText;
		responseText= responseText.replace(/^\s*|\s*$/g,"");
		pairs=responseText.split("|");
		//alert(responseText);
		elements=document.getElementsByTagName("select");
		//alert(elements.length);
		
		for(i=0;i<elements.length;i++){
			element=elements[i];
			//alert(element.className+" "+elementId);			
			if(element.className==elementId){
				element.innerHTML="";
				option=document.createElement("option");
				option.value="";
				element.appendChild(option);
				for(j=0;j<pairs.length;j++){
					pair=pairs[j].split('=');
					key=pair[0];
					value=pair[1];
					option=document.createElement("option");
					option.value=key;
					option.innerHTML=value;
					element.appendChild(option);
				}												
			}
		}
	}
}

function stateChanged(){
	if (xmlhttp.readyState==4){
		responseText=xmlhttp.responseText;
		document.getElementById(elementId).innerHTML=responseText;
	}
}

function enableRefColumns(checkBox){	
	refId='refColumn_'+checkBox.value;	
	refColumnSelect=document.getElementById(refId);
	refColumnSelect.disabled=!refColumnSelect.disabled;
}
	
function verificaFormulario(){	
	refTable=document.getElementById("refTable");
	if(refTable.selectedIndex==0){
		alert('Seleccione la tabla de referencia');
		return false;
	}
	
	if(!verificarCheckBox()) return false;
	if(!verificarSelects()) return false;
	return true;
}

function verificarCheckBox(){
	elements=document.getElementsByTagName("input");
	checkedBoxesCount=0;
	for(i=0;i<elements.length;i++){
		element=elements[i];
		if(element.type=="checkbox" && element.checked){
			checkedBoxesCount++;
			refId='refColumn_'+element.value;
			refColumnSelect=document.getElementById(refId);
			if(refColumnSelect.value==''){
				alert('Debe seleccionar la columna de referencia para: '+element.value);
				return false;
			}
		}
	}
	if(checkedBoxesCount==0){
		alert('Debe seleccionar al menos una columna');
		return false;
	}
	return true;
}

function verificarSelects(){
	return true;
}

function loadColumns(){
	tbl_columnas=window.opener.document.getElementById('tbl_columnas');
	elements=tbl_columnas.getElementsByTagName('input');
	rows=new Array();
	
	for(i=0,j=0;i<elements.length;i++){
		element=elements[i];
		if(element.name=='columnDefinition[]'){
			rows[j]=element.value.split('|');
			addColumn(rows[j][0],rows[j][1],rows[j][2]);			
			j++;
		}		
	}	
}


function addColumn(nombre, tipo,longitud) {
	tbl = document.getElementById('tbl_constraint');
	var lastRow = tbl.rows.length;
	var iteration = lastRow;
	var row = tbl.insertRow(lastRow);

	idGenerator=Math.random();
	
	row.id = idGenerator;

	var cell = row.insertCell(0);
	var checkbox = document.createElement("input");
	//checkbox.name="columns[]";
	//checkbox.value=nombre;
	//checkbox.type="checkbox";
	//checkbox.setAttribute("onclick","enableRefColumns(this)");
	//cell.appendChild(checkbox);
	cell.innerHTML='<input type="checkbox" name="columns[]" onclick="enableRefColumns(this)" value="'+nombre+'">';
	
	var cell = row.insertCell(1);
	var cnombre = document.createTextNode(nombre);
	cell.appendChild(cnombre);

	if(longitud){
		tipo+='('+longitud+')';
	}
	
	var cell = row.insertCell(2);
	var ctipo = document.createTextNode(tipo);
	cell.appendChild(ctipo);	
	
	var cell = row.insertCell(3);
	var select = document.createElement("select");
	select.id="refColumn_"+nombre;
	select.disabled="disabled";
	select.name="refcolumns[]";
	select.className="refColumns";
	
	var option=document.createElement("option");
	option.text="Seleccione la tabla";
	select.appendChild(option);
	
	cell.appendChild(select);	
	
}


function buildFK(){
	
	if(!verificaFormulario()){
		return false;
	}
	
	name=document.getElementById('cname').value;
	
	statement="CONSTRAINT "+name+" ";
	statement+="FOREIGN KEY";
	statement+="(";
	
	elements=document.getElementsByTagName('input');
	firstLoop=true;
	for(i=0,j=0;i<elements.length;i++){
		element=elements[i];
		if(element.name=='columns[]'&&element.checked){
			if(!firstLoop){
				statement+=',';	
			}
			statement+=element.value;
			firstLoop=false;
		}		
	}
	statement+=") ";
		
	refTable=document.getElementById("refTable").value;
	statement+="REFERENCES "+refTable;
	
	statement+="(";
	elements=document.getElementsByTagName('select');
	firstLoop=true;
	for(i=0,j=0;i<elements.length;i++){
		element=elements[i];
		if(element.name=='refcolumns[]'&&!element.disabled){
			if(!firstLoop){
				statement+=',';	
			}
			statement+=element.value;
			firstLoop=false;
		}		
	}
	statement+=")";
			
	tbl = window.opener.document.getElementById('tbl_restricciones');
	var lastRow = tbl.rows.length;
	var iteration = lastRow;
	var row = tbl.insertRow(lastRow);

	idGenerator=Math.random();	
	row.id = idGenerator;

	var cell = row.insertCell(0);
	//var nombre = document.createTextNode(name);
	//cell.appendChild(nombre);
	cell.innerHTML=name;

	var cell = row.insertCell(1);
	//var nombre = document.createTextNode(statement);
	//cell.appendChild(nombre);
	cell.innerHTML=statement;
	
	var cell = row.insertCell(2);
	
	//var alink = document.createElement("a");
	//var img = document.createElement("img");
	//img.src=imgDir+"/document_delete.png";
	//img.alt="Borrar";
	//img.title="Borrar";
	//img.width=15;
	//img.height=15;
	//img.border=0;
	
	//alink.appendChild(img);
	//alink.href="#";
	//alink.setAttribute("onClick","delRowRestricciones('"+row.id+"')");
	//cell.appendChild(alink);
	
	//var nombre = document.createElement("input");
	//nombre.type="hidden";
	//nombre.name="constraintDefinition[]";
	//nombre.id="constraintDefinition"+idGenerator;
	
	//definition=statement;
	//nombre.value=definition;
	
	//cell.appendChild(nombre);
	
	deleteIconHtml='<a href="#" onclick="delRowRestricciones(\''+row.id+'\')">';
	deleteIconHtml+='<img src="'+imgDir+'/document_delete.png" title="Borrar" alt="Borrar" width="15" height="15" border="0"</a>';
	
	definition=statement;
	var hiddenFildHtml='<input type="hidden" name="columnDefinition[]" id="columnDefinition"'+idGenerator+' value="'+definition+'">';
	cell.innerHTML=deleteIconHtml+hiddenFildHtml;		
	window.close();
}
